package com.sibu.yx.promotion.service.biz;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.exceptions.ClientException;
import com.doubo.common.model.SmsStringResult;
import com.doubo.common.util.ExceptionUtil;
import com.sibu.yx.promotion.common.enums.AliYunSmsTemplateEnum;
import com.sibu.yx.promotion.service.config.AliYunSmsProperties;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by wangyi on 2018/01/24
 * 阿里云[云通信]短信服务类
 */
@Slf4j
@Component
public class AliyunSmsBiz {

    @Autowired
    private AliYunSmsProperties aliyunSmsProperties;

    /**
     * 发送短信
     *
     * @param phone 手机号
     * @return
     */
    public SmsStringResult sendSmsTemplate(AliYunSmsTemplateEnum smsTemplate, String phone, String... params) {
        SmsStringResult msgResult = new SmsStringResult();
        SendSmsResponse response;
        try {
            response = sendSmsInternal(smsTemplate, phone, params);
        } catch (Exception e) {
            msgResult.setCode("-1");
            msgResult.setMsg(ExceptionUtil.getAsString(e));
            log.error("Send Sms error, the phone is [{}], Occt some Exception:{}", phone, ExceptionUtil.getAsString(e));
            return msgResult;
        }
        msgResult.setCode(response.getBody().getCode());
        msgResult.setMsg(response.getBody().getMessage());
        return msgResult;
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     * @throws ClientException
     */
    private SendSmsResponse sendSmsInternal(AliYunSmsTemplateEnum smsTemplate, String phone, String... params) throws Exception {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(aliyunSmsProperties.getSignName());
        request.setTemplateCode(smsTemplate.getSmsTemplateCode());
        request.setTemplateParam(smsTemplate.format(params));
        return newClient().sendSms(request);
    }


    private com.aliyun.dysmsapi20170525.Client newClient() throws Exception {
        Config config = new Config();
        config.accessKeyId = aliyunSmsProperties.getAppKey();
        config.accessKeySecret = aliyunSmsProperties.getAppSecret();
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
